import * as THREE from '../../../../modules/three/three.module.js'
import {
  bufferAttributeToVectors,
  bufferAttributeToVectorsV2,
  getPolygonGeometry,
  holeMtl
} from "../util/StaticMethods.js";
import Earcut from "../util/Earcut.js";
// import {BoolPolygonsUtil} from "../util/bool-polygons-util.js";
import {WorldConfig} from "../CommonConsts.js";

// 不可喷涂区 网格, 直接添加在场景树的根节点下面，是零变换的
export default class HoleMesh extends THREE.Mesh {
  /**
   * @type {THREE.Vector3[]}
   * @private
   */
  _tmpVectors = []
  _tmpVectorsLocal = []
  _bacPosAttr
  /**
   * @type {WorkArea}
   */
  areaObj
  /**
   * @type {WorkArea}
   */
  vo

  constructor(geometry, material) {
    super(geometry, material)
    this.renderOrder = WorldConfig.order_hole
  }
  /**
   * @param {WorkArea} workArea
   */
  setFromVO(workArea) {
    this.vo = workArea
    const geometry = getPolygonGeometry(workArea.verts, workArea.planeMat, workArea.facing)
    const material = holeMtl.clone()
    this.geometry = geometry
    this.material = material
    return this
  }
  /**
   * 通过拖拽图形的顶点来改变 图形形状
   * @param {number} index 索引
   * @param {THREE.Vector3} pos 被拖拽顶点的新位置
   */
  updateShapeByVertDragging(index, pos) {
    const posAttr = this.geometry.getAttribute('position')
    posAttr.setXYZ(index, pos.x, pos.y, pos.z)
    posAttr.needsUpdate = true
  }

  // 更新 该网格对应的 WorkArea 数据，调用时机：鼠标弹起，结束拖拽顶点，形变结束
  updateModelData() {
    this.geometry.computeBoundingBox()
    this.geometry.computeBoundingSphere()
    const workArea = this.vo
    const localVectors = []
    const arr = workArea.verts[0]
    const holeIndices = workArea.verts[1]
    const arrFlatted = []
    // arr.length = 0
    const vectors = bufferAttributeToVectorsV2(this.geometry.getAttribute('position'), this._tmpVectors)
    vectors.forEach((vector, index) => {
      const point = this._tmpVectorsLocal[index].copy(vector).applyMatrix4(workArea.planeMatInv)
      localVectors.push(point)
      // arr.push({x: point.x, y: point.y})
      arr[index].x = point.x
      arr[index].y = point.y
      arrFlatted.push(point.x, point.y)
    })
    workArea.oldLocalBox3.copy(workArea.localBox3)
    workArea.localBox3.setFromPoints(localVectors)

    // 拖拽图形的顶点后，图形的凹凸可能发生变化，需要重新三角化
    let triangles = Earcut.triangulate(arrFlatted, holeIndices)
    if (this.geometry.index.array.length !== triangles.length) {
      this.geometry.setIndex(triangles)
    } else {
      this.geometry.index.set(triangles)
      this.geometry.index.needsUpdate = true
    }

  }

  // 备份形状
  backupShape() {
    this._bacPosAttr = this.geometry.getAttribute('position').clone()
    this._tmpVectors = bufferAttributeToVectors(this._bacPosAttr)
    this._tmpVectorsLocal = this._tmpVectors.map(it => new THREE.Vector3())
  }

  // 从备份中恢复形状
  restoreShapeFromBackup() {
    this.geometry.getAttribute('position').copy(this._bacPosAttr)
    this.geometry.getAttribute('position').needsUpdate = true
  }

  /**
   * 获取自相交交点坐标列表，相对于本地坐标空间
   * @return {{x: number, y: number}[]} 平面坐标系内的二维坐标
   */
  getSelfIntersectPoints() {
    // const workArea = this.vo
    // const arr = []
    // const vectors = bufferAttributeToVectors(this.geometry.getAttribute('position'))
    // vectors.forEach(vector => {
    //   const point = vector.clone().applyMatrix4(workArea.planeMatInv)
    //   arr.push({x: point.x, y: point.y})
    // })
    // return BoolPolygonsUtil.getContourSelfIntersectedPoints(arr)
    return []
  }
}
